package com.ch.ms.server.login.packet.handler;


import com.ch.ms.data.domain.character.ChmsCharacter;
import com.ch.ms.dto.MapleCharacterDto;
import com.ch.ms.server.base.MaplePacketHandler;
import com.ch.ms.server.base.client.MapleClientSession;
import com.ch.ms.server.packet.LoadCharactersPacket;
import com.ch.ms.server.packet.LoadCharactersResPacket;
import com.ch.ms.service.account.ChmsAccountService;
import com.ch.ms.service.character.ChmsCharacterCacheService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.ch.ms.server.base.client.ClientAttributeKeys.LOGGED_ATTR_KEY;

/**
 * 读取游戏角色列表
 */
@Component
@Slf4j
public class LoadCharactersPacketHandler implements MaplePacketHandler<LoadCharactersPacket> {

    private final ChmsAccountService accountService;

    private final ChmsCharacterCacheService characterCacheService;

    @Autowired
    public LoadCharactersPacketHandler(ChmsAccountService accountService, ChmsCharacterCacheService characterCacheService) {
        this.accountService = accountService;
        this.characterCacheService = characterCacheService;
    }

    @Override
    public void handle(MapleClientSession clientSession, LoadCharactersPacket packet) {

        if (!clientSession.getBooleanAttribute(LOGGED_ATTR_KEY, false))
            log.error("客户端 {} 尚未登录!", clientSession);
        else {
            List<ChmsCharacter> chmsCharacters = accountService.getCharacters(clientSession.getAccount());
            characterCacheService.saveAll(chmsCharacters);
            List<MapleCharacterDto> characters = Lists.newArrayListWithCapacity(chmsCharacters.size());
            chmsCharacters.forEach(chmsCharacter -> characters.add(MapleCharacterDto.builder().build().from(chmsCharacter)));
            clientSession.sendPacket(LoadCharactersResPacket.builder().characters(characters).build());
        }
    }
}
